package com.api.gbhg.zengping.action;


import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.liwenjun.VersionFlowUtil;
import com.api.gbhg.zengping.common.CommonDao;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.workflow.WorkflowVersion;

import java.util.*;

import static com.api.gbhg.lbj.tool.Tools.*;

/**
 * @program: gbhg-oa
 * @description: 经费来源Action
 * @author: Mr.zeng
 * @create: 2021-02-19 14:20
 **/
public class MoneySources extends BaseBean implements Action {

    public static final Logger LOGGER = LoggerFactory.getLogger("gbhg");
    private static String YJ ;//科目级别
    private static String XJ ;//科目下级
    @Override
    public String execute(RequestInfo requestInfo) {
        LOGGER.info("========================预算审批节点同步明细到经费来源表==============================================");

        BaseBean baseBean = new BaseBean();
        YJ = baseBean.getPropValue("Verification","yj");
        XJ = baseBean.getPropValue("Verification","xj");
        LOGGER.info("财政拨款核批层级 YJ="+YJ+"  XJ="+XJ);

        String requestid = requestInfo.getRequestid();
        //得到明细表名
        DetailTable[] detailTables = CommonDao.getDetailTables(requestInfo);
        //当前流程表名-类似 formtable_main_22  (批量提交时这种方法获取不到主表名)requestInfo.getRequestManager().getBillTableName()
        String billTableName = requestInfo.getRequestManager().getBillTableName();
        billTableName = detailTables[0].getTableDBName().substring(0, detailTables[0].getTableDBName().indexOf("_dt1"));
        RecordSet rs = CommonDao.selectByRequestId(new RecordSet(), billTableName, requestid);
        rs.next();
        String mainid = rs.getString("id");
        String sbdw = rs.getString("sbdw");
        String workflowid = requestInfo.getWorkflowid();
        //02流程特殊处理
        String workflowid02 = getPropValue("FormationWorkflowid", "BZ02Workflowid");//读取配置文件
        String activeworkflowid02= WorkflowVersion.getActiveVersionWFID(workflowid02);
        //05流程特殊处理
        String workflowid05 = getPropValue("FormationWorkflowid", "BZ05Workflowid");//读取配置文件
        String activeworkflowid05= WorkflowVersion.getActiveVersionWFID(workflowid05);
        //18流程特殊处理
        String workflowid18 = getPropValue("FormationWorkflowid", "BZ18Workflowid");//读取配置文件
        String activeworkflowid18= WorkflowVersion.getActiveVersionWFID(workflowid18);
        //19流程特殊处理
        String workflowid19 = getPropValue("FormationWorkflowid", "BZ19Workflowid");//读取配置文件
        String activeworkflowid19= WorkflowVersion.getActiveVersionWFID(workflowid19);
        //预算追加流程
        String workflowid20 = baseBean.getPropValue("FormationWorkflowid", "BZ20Workflowid");//读取配置文件
        String activeworkflowid20= WorkflowVersion.getActiveVersionWFID(workflowid20);

        RecordSet recordSetS = new RecordSet();
        RecordSet recordSetD = new RecordSet();
        RecordSet rss2 = new RecordSet();
        rss2.executeUpdate("delete from uf_jingfeilaiyuan where lcid =" + requestid);
        rss2.next();
        //02和19流程 明细表 dt_5 dt_6
        if (workflowid.equals(activeworkflowid02)||workflowid.equals(activeworkflowid19)||workflowid.equals(activeworkflowid20)) {
            // 上年结转核批明细
            recordSetS = CommonDao.selectByDetailTable(detailTables[4].getTableDBName(), mainid);
            // 当年预算核批明细
            recordSetD = CommonDao.selectByDetailTable(detailTables[5].getTableDBName(), mainid);
        }else if(workflowid.equals(activeworkflowid05)){
            // 上年结转核批明细
            recordSetS = CommonDao.selectByDetailTable(detailTables[3].getTableDBName(), mainid);
            // 当年预算核批明细
            recordSetD = CommonDao.selectByDetailTable(detailTables[4].getTableDBName(), mainid);
        }else if(workflowid.equals(activeworkflowid18)){
            // 上年结转核批明细
            recordSetS = CommonDao.selectByDetailTable(detailTables[6].getTableDBName(), mainid);
            // 当年预算核批明细
            recordSetD = CommonDao.selectByDetailTable(detailTables[7].getTableDBName(), mainid);
        }else{
            // 上年结转核批明细
            recordSetS = CommonDao.selectByDetailTable(detailTables[2].getTableDBName(), mainid);
            // 当年预算核批明细
            recordSetD = CommonDao.selectByDetailTable(detailTables[3].getTableDBName(), mainid);
        }
        Map<String, Object>[] maps = new HashMap[recordSetS.getArray().size() + recordSetD.getArray().size()];
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);//当前年份
        //int year1 = calendar.get(Calendar.YEAR) - 1;//上年年份
        int year1 = calendar.get(Calendar.YEAR);//上年年份 huangwm
        int count = 0;

        // 上年结转核批明细
        while (recordSetS.next()) {
            int sum1 = 0;
            int sum2 = 0;
            maps[count] = new HashMap<>();
            //支出渠道
            String zcqd = recordSetS.getString("zcqd");
            //收入类型
            String srlx = recordSetS.getString("srlx");
            //功能科目_新
            String gnkm = "";
            //中央财政拨款项目
            String zyczbksr = recordSetS.getString("zyczbksr");
            //地方财政拨款项目上年结转
            String dfczbkxmsnjz = recordSetS.getString("dfczbkxmsnjz");
            if (srlx.equals("0")) {//0：中央
                if (StringUtils.isNotBlank(zyczbksr)) {
                    String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                    sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                    sum2 = Integer.parseInt(sta[1]);//表id
                    if (sum1 == Integer.parseInt(YJ)) {
                        gnkm = getSubjectsGnkm(sum2);
                        LOGGER.info("gnkm" + gnkm);
                    } else if (sum1 == Integer.parseInt(XJ)) {
                        gnkm = getSubjectsGnkm(getSubjectsGnkm2(sum2));
                        LOGGER.info("gnkm" + gnkm);
                    }
                }
            } else if (srlx.equals("1")) {//1:非中央
                RecordSet rs1 = theCentral(zcqd, year1, sbdw);
                gnkm = rs1.getString("gnkm");
                LOGGER.info("gnkm" + gnkm);
            }
            LOGGER.info("上年--收入类型:" + srlx + "功能科目:" + gnkm + "sum1" + sum1 + "sum2" + sum2);

            //核批金额
            String hpje = recordSetS.getString("hpje");
            maps[count].put("sbdw", rs.getString("sbdw"));
            maps[count].put("nd", rs.getString("ysnd"));
            //来源类型
            maps[count].put("zcqd", zcqd);
            //功能科目
            maps[count].put("gnkm", gnkm);
            //金额
            maps[count].put("je", hpje);
            //剩余额度
            maps[count].put("syed", hpje);
            //冻结金额
            maps[count].put("djje", 0);
            //预算来源类型
            maps[count].put("yslylx", "上年结转核批");
            //收入类型
            maps[count].put("srlx", srlx);
            //地方财政拨款项目上年结转
            maps[count].put("dfczbkxm", dfczbkxmsnjz);
            //中央财政拨款收入
            maps[count].put("zyczbksr", zyczbksr);
            maps[count].put("lcid", requestid);
            count++;
        }

        // 当年预算核批明细
        while (recordSetD.next()) {
            int sum1 = 0;
            int sum2 = 0;
            maps[count] = new HashMap<>();
            //支出渠道
            String zcqd = recordSetD.getString("zcqd");
            //收入类型
            String srlx = recordSetD.getString("srlx");
            //功能科目_新
            String gnkm = "";
            //中央财政拨款收入
            String zyczbksr = recordSetD.getString("zyczbksr");
            //地方财政拨款项目当年预算
            String dfczbkxmdnys = recordSetD.getString("dfczbkxmdnys");
            if (srlx.equals("0")) {//0：中央
                if (StringUtils.isNotBlank(zyczbksr)) {
                    String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                    sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                    sum2 = Integer.parseInt(sta[1]);//表id
                    if (sum1 == Integer.parseInt(YJ)) {
                        gnkm = getSubjectsGnkm(sum2);
                    } else if (sum1 == Integer.parseInt(XJ)) {
                        gnkm = getSubjectsGnkm(getSubjectsGnkm2(sum2));
                    }
                }
            } else if (srlx.equals("1")) {//1:非中央
                RecordSet rs1 = theCentral(zcqd, year, sbdw);
                rs1.next();
                gnkm = rs1.getString("gnkm");
            }
            LOGGER.info("当年--收入类型:" + srlx + "功能科目:" + gnkm + "sum1" + sum1 + "sum2" + sum2);
            //核批金额
            String hpje = recordSetD.getString("hpje");
            maps[count].put("sbdw", rs.getString("sbdw"));
            maps[count].put("nd", rs.getString("ysnd"));
            //来源类型
            maps[count].put("zcqd", zcqd);
            //功能科目
            maps[count].put("gnkm", gnkm);
            //金额
            maps[count].put("je", hpje);
            //剩余额度
            maps[count].put("syed", hpje);
            //冻结金额
            maps[count].put("djje", 0);
            //预算来源类型
            maps[count].put("yslylx", "当年预算核批");
            //收入类型
            maps[count].put("srlx", srlx);
            //地方财政拨款项目当年预算
            maps[count].put("dfczbkxm", dfczbkxmdnys);
            //中央财政拨款收入
            maps[count].put("zyczbksr", zyczbksr);
            maps[count].put("lcid", requestid);
            count++;
        }
        LOGGER.info(JSONObject.toJSONString(maps));
        if (maps.length > 0) {
            RecordSet rss = new RecordSet();
            rss.executeUpdate("delete from uf_jingfeilaiyuan where lcid =" + requestid);
            rss.next();
            // 存储数据到经费来源表
            boolean b = storageDateToJingfeiLy(maps);
            if (!b) {
                LOGGER.info("============================预算审批节点同步明细3,4到经费来源表错误======================================");
                requestInfo.getRequestManager().setMessagecontent("预算审批节点同步明细3,4到经费来源表出现错误");
                requestInfo.getRequestManager().setMessageid("1");
                return FAILURE_AND_CONTINUE;
            }
            //2022年7月6日 huangwm 增加用于写入到经费额度版本表
            String jingfei = "INSERT INTO [dbo].[uf_jingfeiVersion]\n" +
                    "           ([requestId],[ybx],[sydw],[lcbj],[lcjlid],[bmzcjjfl],[zfjjfl],[nd],[ze],[syed],[dj],[sbdw],[xmmc],[gkdw],[version])\n" +
                    "select [requestId],[ybx],[sydw],[lcbj],[lcjlid],[bmzcjjfl],[zfjjfl],[nd],[ze],[syed],[dj],[sbdw],[xmmc],[gkdw]," +1+"\n"+
                    "from uf_jingfei where lcjlid="+requestid;
            String jingfeilaiyuan = "INSERT INTO [dbo].[uf_jingfeilaiyuanVersion]\n" +
                    "           ([requestId],[sbdw],[lcbj],[nd],[gnkm],[yslylx],[dfczbkxm],[zyczbkxm],[je],[syed],[djje],[lcid],[zcqd],[zyczbksr],[lylx],[srlx],[version])\n" +
                    "select [requestId],[sbdw],[lcbj],[nd],[gnkm],[yslylx],[dfczbkxm],[zyczbkxm],[je],[syed],[djje],[lcid],[zcqd],[zyczbksr],[lylx],[srlx]," +1+"\n"+
                    "from uf_jingfeilaiyuan where lcid="+requestid;
            rss.executeUpdate(jingfei);
            rss.executeUpdate(jingfeilaiyuan);
        }
        LOGGER.info("同步人员经费成功>"+requestid);
        return SUCCESS;
    }

    /* *
     * @Author 尚展锋
     * @Description //检测Map空的key删除
     * @Date 17:31 2020/9/5
     * @Param [param]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> removeNullString(Map<String, Object> param) {
        try {
            Iterator<String> it = param.keySet().iterator();
            while (it.hasNext()) {
                Object ele = it.next();
                if (param.get(ele).toString().trim().equals("")) {
                    //hashMap.remove(ele);    //出错 修改了映射结构 影响了迭代器遍历
                    it.remove();              //用迭代器删除 则不会出错
                }
            }
            return param;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean storageDateToJingfeiLy(Map[] maps) {
        boolean flag = false;
        for (int i = 0; i < maps.length; i++) {
            Map map = removeNullString(maps[i]);
            Set set = map.keySet();
            List<String> listField = new ArrayList<String>(set);
            // 上年结转
            Collection<String> valueCollection = map.values();
            List<String> valueList = new ArrayList<>(valueCollection);
            // 存储数据到经费来源表
            RecordSetTrans rst = new RecordSetTrans();
            String uf_jingfeilaiyuansql = VersionFlowUtil.getInsertSql(listField, "uf_jingfeilaiyuan");
            try {
                rst.executeUpdate(uf_jingfeilaiyuansql, valueList.toArray());
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("同步经费来源sql---->" + uf_jingfeilaiyuansql + valueCollection);
                LOGGER.info("errorsql==" + e.toString());
                flag = false;
            }
            flag = true;
        }
        return flag;
    }

    public static void main(String[] args) {
        String str = "formtable_main_22_dt1";
        String dt1 = str.substring(0, str.indexOf("_dt1"));
        System.out.println(dt1);
    }
}
